package com.ruoyi.teaching.service.impl;

import java.util.*;

import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.teaching.bo.InsertInterviewMasteryBo;
import com.ruoyi.teaching.domain.InterviewMasteryDetail;
import com.ruoyi.teaching.mapper.InterviewMasteryDetailMapper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.teaching.mapper.InterviewMasteryMapper;
import com.ruoyi.teaching.domain.InterviewMastery;
import com.ruoyi.teaching.service.IInterviewMasteryService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 面试掌握情况记录Service业务层处理
 *
 * @author ruoyi
 * @date 2024-04-02
 */
@Service
public class InterviewMasteryServiceImpl implements IInterviewMasteryService
{
    @Autowired
    private InterviewMasteryMapper interviewMasteryMapper;
    @Autowired
    private InterviewMasteryDetailMapper interviewMasteryDetailMapper;

    /**
     * 查询面试掌握情况记录
     *
     * @param id 面试掌握情况记录主键
     * @return 面试掌握情况记录
     */
    @Override
    public InterviewMastery selectInterviewMasteryById(Long id)
    {
        return interviewMasteryMapper.selectInterviewMasteryById(id);
    }

    /**
     * 查询面试掌握情况记录列表
     *
     * @param interviewMastery 面试掌握情况记录
     * @return 面试掌握情况记录
     */
    @Override
    public List<InterviewMastery> selectInterviewMasteryList(InterviewMastery interviewMastery)
    {
        return interviewMasteryMapper.selectInterviewMasteryList(interviewMastery);
    }

    /**
     * 新增面试掌握情况记录
     *
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertInterviewMastery(InsertInterviewMasteryBo interviewMasteryBo)
    {
        //1.新增一方（面试记录）
        InterviewMastery interviewMastery = new InterviewMastery();
        String communicationInterviewMastery = interviewMasteryBo.getCommunicationInterviewMastery();
        interviewMastery.setCommunicationMastery(communicationInterviewMastery);
        interviewMastery.setCommunicationScore(computeCommunicationScore(communicationInterviewMastery));
        interviewMastery.setCreateTime(new Date());
        interviewMastery.setUserId(interviewMasteryBo.getUserId());
        interviewMastery.setCreateBy(SecurityUtils.getUsername());

        interviewMasteryMapper.insertInterviewMastery(interviewMastery);



        //将selectedInterviewList转成map<Long,String>
        //key:面试题id   value:掌握情况->3,4->4分
        Map<Long, String> map = new HashMap<>(interviewMasteryBo.getSelectedInterviewList().size());
        for (String str : interviewMasteryBo.getSelectedInterviewList()) {
            //str->面试题id,掌握程度
            String[] split = str.split(",");
            Long interviewId = Long.valueOf(split[0]);
            String degree = split[1];
            //判断是否存在
            if (map.containsKey(interviewId)) {
                //取出原有字符拼接
                map.put(interviewId, map.get(interviewId) + "," + degree);
            } else {
                map.put(interviewId, degree);
            }
        }


        Long id = interviewMastery.getId();
        //2.新增多方（面试记录详情-维护关系）
        for (Map.Entry<Long, String> entry : map.entrySet()) {
            InterviewMasteryDetail detail = new InterviewMasteryDetail();
            detail.setQuestionId(entry.getKey());
            detail.setDegree(entry.getValue());
            detail.setInterviewMasteryId(id);
            detail.setScore(computeScore(entry.getValue()));
            detail.setUserId(interviewMasteryBo.getUserId());
            detail.setCreateTime(interviewMastery.getCreateTime());
            interviewMasteryDetailMapper.insertInterviewMasteryDetail(detail);
        }

        //3.更新面试记录技能平均分
        interviewMastery.setAvgScore(computeAvgScore(map));
        interviewMasteryMapper.updateInterviewMastery(interviewMastery);
        return 1;
    }

    private Integer computeAvgScore(Map<Long,String> map) {
        if (ObjectUtils.isEmpty(map)) {
            return 0;
        }
        //计算每个面试题得分->计算平均分
        Integer result = 0;
        for (Map.Entry<Long, String> entry : map.entrySet()) {
            Long interviewId = entry.getKey();
            String degrees = entry.getValue();
            //单个面试题得分
            Integer score = computeScore(degrees);
            result+=score;
        }
        if (map.size()==0) {
            return 0;
        }

        return result/map.size();
    }

    private Integer computeScore(String degrees) {
        return Arrays.stream(degrees.split(",")).mapToInt(degree->{
            if ("1".equals(degree)) {
                return 0;
            } else if ("2".equals(degree)) {
                return 1;
            } else {
                return 2;
            }
        }).sum();
    }

    private Integer computeCommunicationScore(String communicationInterviewMastery) {
        if (StringUtils.isEmpty(communicationInterviewMastery)) {
            return 0;
        }
        return communicationInterviewMastery.split(",").length;
    }

    /**
     * 修改面试掌握情况记录
     *
     * @param interviewMastery 面试掌握情况记录
     * @return 结果
     */
    @Override
    public int updateInterviewMastery(InterviewMastery interviewMastery)
    {
        interviewMastery.setUpdateTime(DateUtils.getNowDate());
        return interviewMasteryMapper.updateInterviewMastery(interviewMastery);
    }

    /**
     * 批量删除面试掌握情况记录
     *
     * @param ids 需要删除的面试掌握情况记录主键
     * @return 结果
     */
    @Override
    public int deleteInterviewMasteryByIds(Long[] ids)
    {
        return interviewMasteryMapper.deleteInterviewMasteryByIds(ids);
    }

    /**
     * 删除面试掌握情况记录信息
     *
     * @param id 面试掌握情况记录主键
     * @return 结果
     */
    @Override
    public int deleteInterviewMasteryById(Long id)
    {
        return interviewMasteryMapper.deleteInterviewMasteryById(id);
    }
}
